from concurrent.futures import ThreadPoolExecutor
import datetime
from time import time
from utils.logging_tool.log_control import Listing_Error
from utils.mysqlUtils.db_utils import DB



class StarrocksSynchronization:

    """
    Starrocks数据同步服务
    """

    def startrocks_test_server(self, ordersourceid):

        star_time = time()
        # 获取前一天时间
        after_time = (datetime.datetime.now() + datetime.timedelta(days = -2)).strftime('%Y-%m-%d')
        base_id = ordersourceid.split(',')
        count = 0
        for id in base_id:
            startrocks_base = DB("startrocks_db_base")
            cold_base = DB("mysql_db_code_base")
            base_sql = f"select DepartmentId from aml_department_ordersource where OrderSourceId = {int(id)}"
            base_num = cold_base.execute_sql_many(base_sql)[0]["DepartmentId"]
            cold_sql = f"SELECT ErpId, ListingPrice, OrderSourceID, OrderSourceSKU FROM `aml_amazon_product_base_dep{base_num}` " \
                       f"WHERE OrderSourceID = {id} AND AddTime <= '{after_time}';"
            star_sql = f"SELECT ErpId, ListingPrice, OrderSourceID, OrderSourceSKU FROM `aml_amazon_product_base` " \
                       f"WHERE OrderSourceID = {id} AND AddTime <= '{after_time}';"
            cold_res = cold_base.execute_sql_many(cold_sql)
            star_res = startrocks_base.execute_sql_many(star_sql)

            # 创建线程池
            pool = ThreadPoolExecutor()
            for i in cold_res:
                count += 1
                pool.submit(self.data_comparison, i, id, star_res)
            pool.shutdown(True)
        end_time = time()
        print(round(end_time - star_time, 2), 's')
        print(f"共执行{count}次")

        # report = f"执行时间:{now_time()}    \n" \
        #          f"同步Startrocks数据库服务验证  \n" \
        #          f"Stratrocks检测数据{len(res_startrocks)}条 \n" \
        #          f"发现异常数据{len(error_lis)}条  \n" \
        #          f"异常明细:    \n" \
        #          f"{error_lis}"
        # return report

    def data_comparison(self, sale_data, OrderSourceId, cold_ata):

        if sale_data not in cold_ata:
            Listing_Error.logger.error(f"OrderSourceID:{OrderSourceId},{sale_data}>>>>>>>>>存在异常")
        else:
            print(f"OrderSourceID:{OrderSourceId},{sale_data}>>>>>>>>>数据正常")

if __name__ == '__main__':

    # startrocks同步验证
    id = "5005,5098"
    StarrocksSynchronization().startrocks_test_server(id)
